package com.study.chat.support;

import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

@Component
public class Responder {
    @Value("${openai.api.key}")
    private String apiKey;
    private OpenAiService service;
    private static Logger logger
            = Logger.getLogger(Responder.class.toString());

    public Responder(){}

    public String doResponse(String input){
        if(service == null){
            service = new OpenAiService(apiKey);
        }
        final List<ChatMessage> messages = new ArrayList<>();

        //给chatGpt一个资深游戏点评人的身份
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setRole("system");
        chatMessage.setContent("你是一个资深的游戏点评媒体。");
        messages.add(chatMessage);

        //接着给出用户的问题
        ChatMessage userMessage = new ChatMessage();
        userMessage.setRole("user");
        userMessage.setContent(input);
        messages.add(userMessage);

        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .messages(messages)
                .model("text-davinci-002")
                .maxTokens(100)
                .build();

        ChatCompletionResult result = service.createChatCompletion(request);

        String resp = result.getChoices().get(0).getMessage().getContent();
        return resp;

//        ChatCompletionRequest chatCompletionRequest =
//                ChatCompletionRequest.builder()
//                .model("gpt-3.5-turbo")
//                .messages(messages)
//                .n(1)
//                .maxTokens(500)
//                .logitBias(new HashMap<>())
//                .build();

//        StringBuffer sb = new StringBuffer();

//        service.streamChatCompletion(chatCompletionRequest)
//                .doOnError(Throwable::printStackTrace)
//                .blockingForEach(
//                        item->item.getChoices()
//                        .forEach(
//                                item1->sb.append(
//                                        item1.getMessage().getContent()
//                                ))
//                );
//        service.streamChatCompletion(chatCompletionRequest)
//                .doOnError(Throwable::printStackTrace)
//                .blockingForEach(item -> item.getChoices().forEach(item1 -> System.out.print(item1.getMessage().getContent())));

//        return sb.toString();
    }
}
